#include "dg_cli.h"
#include <error.h>
#include <define.h>
#include <wrapfunc.h>
#include <sockfunc.h>
#include <stdio.h>
#include <string.h>


void 
dg_cli(FILE *file, int sockfd, const struct sockaddr *sa, socklen_t salen) {
	char buf[MAX_LINE];
	ssize_t n;
    size_t len;
	for (;;) {
		if (fgets(buf, sizeof(buf), file)) {
            len = strlen(buf);
            if (buf[len-1] == '\n') {
                buf[len-1] = 0;
                len = len -1;
            }
			Sendto(sockfd, buf, len, 0, sa, salen);
			n = Recvfrom(sockfd, buf, sizeof(buf)-1, 0, NULL, NULL);
			buf[n] = 0;
			error_msg(":%s", buf);
		}
	}
}

void 
dg_cliaddr(FILE *file, int sockfd, const struct sockaddr *sa, socklen_t salen) {
	char buf[MAX_LINE];
	ssize_t n;
    size_t len;
    
    char addr[salen];
    struct sockaddr *recvsa = (struct sockaddr*)addr;
    socklen_t recvlen = salen;

	for (;;) {
		if (fgets(buf, sizeof(buf), file)) {
            len = strlen(buf);
            if (buf[len-1] == '\n') {
                buf[len-1] = 0;
                len = len -1;
            }
			Sendto(sockfd, buf, len, 0, sa, salen);

            recvlen = salen;
			n = Recvfrom(sockfd, buf, sizeof(buf)-1, 0, recvsa, &recvlen);
            if (recvlen != salen ||  memcmp(recvsa, sa, recvlen) != 0) {
                error_msg("not server response:%s", sock_ntop(recvsa, recvlen));
                continue;
            }

			buf[n] = 0;
			error_msg(":%s", buf);
		}
	}
}

void 
dg_cliconnect(FILE *file, int sockfd, const struct sockaddr *sa, socklen_t salen) {
	char buf[MAX_LINE];
	ssize_t n;
    size_t len;

    Connect(sockfd, sa, salen); // connected udp socket

    // 若只运行 udp 客户端而不运行服务端，则 read 函数会返回并设置 errno
	for (;;) {
		if (fgets(buf, sizeof(buf), file)) {
            len = strlen(buf);
            if (buf[len-1] == '\n') {
                buf[len-1] = 0;
                len = len -1;
            }
			Write(sockfd, buf, len);
			n = Read(sockfd, buf, sizeof(buf)-1);
			buf[n] = 0;
			error_msg(":%s", buf);
		}
	}
}

void 
dg_cliloop1(int sockfd, const struct sockaddr *sa, socklen_t salen) {
    const int NUM_DATAGRAM = 2000;
    const int BYTES = 1400;
	char buf[BYTES];

    memset(buf, 'E', sizeof(buf));
    for (int i = 0; i < NUM_DATAGRAM; i++)
        Sendto(sockfd, buf, sizeof(buf), 0, sa, salen);
}

